package logic

import (
	"context"
	"errors"
	"shop/cache"
	"shop/models"

	"shop/shopRpc/internal/svc"
	"shop/shopRpc/shopRpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CartAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCartAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartAddLogic {
	return &CartAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CartAddLogic) CartAdd(in *shopRpc.CartAddRequest) (*shopRpc.CartAddResponse, error) {
	// todo: add your logic here and delete this line
	//1.购买数量
	if in.Quantity > 50 {
		return nil, errors.New("购买数量不能超过50件")
	}

	//2.虚拟库存
	if in.Quantity > cache.GetSyncStock(in.GoodsId) {
		return nil, errors.New("虚拟库存不足")
	}
	// 3.判断商品是否存在
	var goods models.Goods
	err := goods.FindGoodsByID(models.DB, in.GoodsId)
	if err != nil {
		return nil, errors.New("商品不存在")
	}
	if !cache.CartGoodsIsExist(in.UserId, in.GoodsId) {
		// 4.将结构体处理成map类型
		goodsMap := map[string]interface{}{
			"id":       goods.ID,
			"name":     goods.Name,
			"price":    goods.Price,
			"status":   goods.Status,
			"img":      goods.Img,
			"quantity": in.Quantity,
		}

		err = cache.CartAdd(in.UserId, in.GoodsId, goodsMap)
		if err != nil {
			return nil, errors.New("购物车添加失败")
		}

	} else {
		err = cache.CartUpdateQuantity(in.UserId, in.GoodsId, in.Quantity)
		if err != nil {
			return nil, errors.New("购物车数量更新失败")
		}
	}

	return &shopRpc.CartAddResponse{
		Success: true,
	}, nil

}
